package com.mooral.web.action.application;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.mooral.bean.Bean;
import com.mooral.bean.Merchants;
import com.mooral.bean.Vouchers;
import com.mooral.context.Context;
import com.mooral.web.action.MooralAction;

public class SiteMapAction extends MooralAction {

	private Document webXml;
	private HttpServletRequest httpRequest;
	
	@Override
	public ActionForward perform(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			Context context) throws Exception {


		request.setAttribute("print", generateSiteMap(request, response) );
		
		return mapping.findForward(ACTION_SUCCESS);
	}

	private String generateSiteMap(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException{
		this.httpRequest = httpRequest; 
		httpResponse.setContentType("application/xml");
		
		String ret = "";
		
		String urlPrefix = "http://"+httpRequest.getServerName();
		
		if(httpRequest.getServerPort()!=80)
			urlPrefix +=":"+httpRequest.getServerPort();
		
		readWebXML();
		
		try{
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.newDocument();
			Element rootElement = document.createElementNS("http://www.sitemaps.org/schemas/sitemap/0.9", "urlset");
			
			document.appendChild(rootElement);
			
			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();
			XPathExpression expr = xpath.compile("/web-app/welcome-file-list/welcome-file/text()");
	
			Object result = expr.evaluate(webXml, XPathConstants.NODESET);
			

			Vouchers vouchers = new Vouchers();
			vouchers.populate(new Bean(), "select * from vouchers");

			for (Bean bean : vouchers) {
				
				Element urlEl = document.createElement("url");
				Element locEl = document.createElement("loc");
				locEl.appendChild(document.createTextNode(urlPrefix + httpRequest.getContextPath() + "/voucher/" + bean.get("slug")));
				urlEl.appendChild(locEl);
				rootElement.appendChild(urlEl);
			}
			
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
	        Transformer transformer = transformerFactory.newTransformer();
	        DOMSource source = new DOMSource(document);
	        
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        StreamResult streamResult =  new StreamResult(baos);
	        transformer.transform(source, streamResult);
			
	        //httpResponse.getOutputStream().println(baos.toString());
	        ret = baos.toString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return ret;
	}


	private void readWebXML() {
		
		if(webXml != null)
			return;
		
		InputStream iStream = httpRequest.getSession().getServletContext().getResourceAsStream("/WEB-INF/web.xml");
		try {
						
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(false);
			
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			Document doc = db.parse(iStream);
			
			webXml = doc;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				iStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
}